document.addEventListener('DOMContentLoaded', function() {
    const videoPlayer = document.getElementById('videoPlayer');
    const playPauseBtn = document.getElementById('playPauseBtn');
    const progressBar = document.getElementById('progressBar');
    const seekBar = document.getElementById('seekBar');
    const currentTimeDisplay = document.getElementById('currentTime');
    const durationDisplay = document.getElementById('duration');
    const muteBtn = document.getElementById('muteBtn');
    const volumeBar = document.getElementById('volumeBar');
    const fullscreenBtn = document.getElementById('fullscreenBtn');
    const speedSelect = document.getElementById('speedSelect');
    const videoList = document.getElementById('videoList');
    
    // 初始化播放器
    function initPlayer() {
        // 从服务器获取视频列表
        fetch('/videos')
            .then(response => response.json())
            .then(videos => {
                if (videos.length > 0) {
                    renderVideoList(videos);
                    // 默认加载第一个视频
                    loadVideo(videos[0].path, videos[0].title);
                }
            })
            .catch(error => console.error('Error fetching video list:', error));
    }
    
    // 渲染视频列表
    function renderVideoList(videos) {
        videoList.innerHTML = '';
        videos.forEach(video => {
            const li = document.createElement('li');
            li.textContent = video.title;
            li.addEventListener('click', () => {
                loadVideo(video.path, video.title);
                // 设置活动状态
                document.querySelectorAll('.video-list li').forEach(item => {
                    item.classList.remove('active');
                });
                li.classList.add('active');
            });
            videoList.appendChild(li);
        });
    }
    
    // 加载视频
    function loadVideo(videoPath, title) {
        videoPlayer.src = `/video/${encodeURIComponent(videoPath)}`;
        videoPlayer.load();
        
        // 更新页面标题
        document.title = `${title} - 视频播放器`;
        
        // 自动播放（注意：许多浏览器会阻止自动播放）
        videoPlayer.play().catch(error => {
            console.log('Autoplay prevented:', error);
        });
    }
    
    // 播放/暂停
    playPauseBtn.addEventListener('click', function() {
        if (videoPlayer.paused) {
            videoPlayer.play();
            playPauseBtn.innerHTML = '<i class="fas fa-pause"></i>';
        } else {
            videoPlayer.pause();
            playPauseBtn.innerHTML = '<i class="fas fa-play"></i>';
        }
    });
    
    // 视频播放状态变化
    videoPlayer.addEventListener('play', function() {
        playPauseBtn.innerHTML = '<i class="fas fa-pause"></i>';
    });
    
    videoPlayer.addEventListener('pause', function() {
        playPauseBtn.innerHTML = '<i class="fas fa-play"></i>';
    });
    
    // 进度条更新
    videoPlayer.addEventListener('timeupdate', function() {
        const value = (videoPlayer.currentTime / videoPlayer.duration) * 100;
        progressBar.value = value;
        seekBar.value = value;
        
        // 更新时间显示
        currentTimeDisplay.textContent = formatTime(videoPlayer.currentTime);
    });
    
    // 视频加载完成后显示总时长
    videoPlayer.addEventListener('loadedmetadata', function() {
        durationDisplay.textContent = formatTime(videoPlayer.duration);
    });
    
    // 点击进度条跳转
    seekBar.addEventListener('input', function() {
        const seekTime = (videoPlayer.duration / 100) * seekBar.value;
        videoPlayer.currentTime = seekTime;
    });
    
    // 音量控制
    volumeBar.addEventListener('input', function() {
        videoPlayer.volume = volumeBar.value;
        
        // 更新静音按钮状态
        if (videoPlayer.volume === 0) {
            muteBtn.innerHTML = '<i class="fas fa-volume-mute"></i>';
        } else {
            muteBtn.innerHTML = '<i class="fas fa-volume-up"></i>';
        }
    });
    
    // 静音/取消静音
    muteBtn.addEventListener('click', function() {
        videoPlayer.muted = !videoPlayer.muted;
        
        if (videoPlayer.muted) {
            muteBtn.innerHTML = '<i class="fas fa-volume-mute"></i>';
            volumeBar.value = 0;
        } else {
            muteBtn.innerHTML = '<i class="fas fa-volume-up"></i>';
            volumeBar.value = videoPlayer.volume;
        }
    });
    
    // 全屏
    fullscreenBtn.addEventListener('click', function() {
        if (!document.fullscreenElement) {
            document.querySelector('.video-player-container').requestFullscreen().catch(err => {
                console.log(`全屏错误: ${err.message}`);
            });
        } else {
            document.exitFullscreen();
        }
    });
    
    // 播放速度
    speedSelect.addEventListener('change', function() {
        videoPlayer.playbackRate = speedSelect.value;
    });
    
    // 格式化时间 (秒 -> MM:SS)
    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const secs = Math.floor(seconds % 60);
        return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    
    // 初始化播放器
    initPlayer();
});